const myWebSocket = () => {
   const socket = new WebSocket('ws://localhost:5000')

   socket.onopen = function (event) {
      socket.send('Hello Server!')
   }

   // setInterval(() => {
   //   socket.send('Hello Server!=' + Date.now());
   // }, 2000)

   // setInterval(() => {
   //   socket.close('1000', '系统负载超额')
   // }, 5000)

   console.log(socket, 'WebSocket')

   socket.onmessage = function (event) {
      console.log('Server response: ', event.data)
   }

   socket.onerror = function (error) {
      console.error('WebSocket Error: ', error)
   }

   socket.onclose = function (event) {
      if (event.wasClean) {
         console.log('Connection closed cleanly, code=', event.code, 'reason=', event.reason)
      } else {
         console.error('Connection died')
      }

      setTimeout(function () {
         myWebSocket()
      }, 2000)
   }

   new Promise((resolve, reject) => {
      setTimeout(function () {
         socket.close(1000, '系统关闭')
         resolve()
      }, 5000)
   })
      .then(res => {
         setTimeout(() => {
            socket.send('我们重新开始吧！')
         }, 2000)
      })
      .catch(err => {
         console.log(err)
      })
}

myWebSocket()
